package com.ruoyi.app.util;

import com.ruoyi.common.VersionUtils;
import com.ruoyi.common.utils.ServletUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.binary.Base64;

@Slf4j
public class AesStrategy {

    //加密
    public String encrypt(String content,String secretKey) throws Exception {
        //低于2.2.0 -> ECB
        if (!compareVersion()){
            return Base64.encodeBase64String(AesUtil.encryptByPKCS5(content.getBytes(), secretKey));
        }
        return AesUtil.gcmEncrypt(content, secretKey);
    }

    //解密
    public String decrypt(String content,String secretKey) throws Exception {
        if (!compareVersion()){
            log.info("使用ECB解密");
            return AesUtil.decrypt(Base64.decodeBase64(content), secretKey);
        }
        log.info("使用GCM解密");
        return AesUtil.gcmDecrypt(content,secretKey);
    }


    /**
     *  是否大于2。2。0
     * @return true -> 新算法， false 原算法
     */
    private boolean compareVersion(){
        String appVersion = ServletUtils.getRequest().getHeader("appVersion");
        return VersionUtils.compareVersion(appVersion, "2.2.2") >= 0 ;
    }
}
